package umaine.ece471.cookbook;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SearchAll extends Activity {
	
	/* PHP script */          
	private static final String SERVER_SCRIPT = "http://mainelyapps.com/mdg/cookbook.php"; 		//location of database server, and script used
	List<String> ret;								//list of strings used later to store output from database search
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("Cookbook-Search for Recipes");
        setContentView(R.layout.search);			//sets layout to customized search.xml file
		this.setTitle("Cookbok - Search for A Recipe");
		Button dbSearch = (Button) findViewById(R.id.searchBtn);		//finds the search button from the layout
		dbSearch.setOnClickListener(new View.OnClickListener() {		//creates an action to be done when the search button is clicked
			
			public void onClick(View v) {
				
				// TODO Auto-generated method stub
				List<NameValuePair> postParams = new ArrayList<NameValuePair>();	//creates a list of NameValuePairs which is passed to the database to search
				
				EditText searchText = (EditText) findViewById(R.id.searchTitle);	//stores the user input for the recipe title search criteria	
				String criteriaTitle =  searchText.getText().toString();
				
				EditText searchText2 = (EditText) findViewById(R.id.searchCreator);	//stores the user input for the recipe creator search criteria
				String criteriaCreator =  searchText2.getText().toString();

				String searchCriteria=criteriaTitle+"_"+criteriaCreator;			//creates a single string from the recipe name and creator search criteria
																					//this is needed due to the way the database was set up
				
			
				postParams.add(new BasicNameValuePair ("op","search"));				//lets the database know that searching will be done instead of storage
				postParams.add(new BasicNameValuePair ("recipename_creator",searchCriteria));	//sends the search criteria to the database
		
					try {
						ret = httpRequest(postParams);									//attempts to run httpRequest in order to communicate with the server and search the database
															
					} catch (Exception e){
						throw new RuntimeException();									//throws an exception if an error occurs during the server request
					}
					
					String[] recipes = new String[ret.size()];							//creates an array of Strings that will store the output from the database search
					for(int i =0; i<ret.size(); i++){									//stores strings from List output into the recipes String array
						recipes[i]=ret.get(i);
					}
					Intent outgoingIntent = new Intent(SearchAll.this, RecipeLister.class);	//sets up an intent which will populate the list view from the search output
					outgoingIntent.putExtra("recipes", recipes);						//sends the array of strings to the intent for listView population
					
					startActivity(outgoingIntent);										//starts RecipeLister 
				}
			
				
			
		});
		

        
    }
    
    
    public static List<String> httpRequest (List<? extends NameValuePair> postParams)				//function that communicates with the database server either for storage or searching
			throws Exception{
		HttpClient client = new DefaultHttpClient();												//creates a http client
		HttpPost request = new HttpPost(SERVER_SCRIPT);												//creates a http request, which is sent to the server(found using php script)
		List<String> ret = new ArrayList<String>();													//creates an array list of strings, which will store the output of the database communication
		
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParams);
						
		request.setEntity(formEntity);																//sets the request to be sent to the server
		HttpResponse response = client.execute(request);											//executes the request
		BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 	//stores output from database request into a bufferedreader
		
		String line = "";
		
		while((line = in.readLine()) != null){														//searches through entire output of the bufferedreader output
			ret.add(line);																			//adds the output one string at a time into the array list of strings ret
		}
		
		in.close();																					//closes the bufferedreader
		return ret; 																				//returns the array list of strings, ret
    }
    
    

}